let loader = PIXI.loader
//加载资源
loader.add(['mine1.jpg']).load(setup)
function setup() {
  let options = {
    width: 800,
    height: 550
  }
  // 创建一个 Pixi应用
  const app = new PIXI.Application(options)
  document.body.appendChild(app.view)

  // holder to store the aliens
  const aliens = []

  // 检测碰撞，创建Bump实例，用于碰撞检测
  let b = new Bump(PIXI)

  // 获取舞台
  let stage = app.stage
  // 容器
  let blocks = undefined

  // 组合图片
  function loadMine() {
    // 图片
    let base = PIXI.utils.TextureCache['mine1.jpg']
    let texture = new PIXI.Texture(base)
    texture.frame = new PIXI.Rectangle(1, 175, 86, 86)

    let texture2 = new PIXI.Texture(base)
    texture2.frame = new PIXI.Rectangle(1, 1, 86, 86)

    let texture3 = new PIXI.Texture(base)
    texture3.frame = new PIXI.Rectangle(88, 88, 86, 86)

    let x = 10,
      y = 15,
      // 10%的雷
      mineSize = 15

    // 格子
    let gridMap = []

    for (let i = 0; i < x; i++) {
      var rows = []
      for (let j = 0; j < y; j++) {
        let rocket = new PIXI.Sprite(texture)
        //Position the rocket sprite on the canvas
        rocket.x = j * 50
        rocket.y = i * 50

        rocket._mineX = j
        rocket._mineY = i
        rocket._mineMark = false

        rocket.width = 50
        rocket.height = 50

        // 点击有效
        rocket.interactive = true
        // 鼠标移动上去变成小手
        rocket.buttonMode = true
        rocket.on('click', onClick)

        rocket.on('rightclick', rightClick)

        //Add the rocket to the stage
        stage.addChild(rocket)

        rows[j] = rocket
      }
      gridMap[i] = rows
    }

    console.log(gridMap)

    // 是否初始化过
    let initMineFlag = false
    // 地图
    let mineMap = [],
      mm = {},
      mmLength = 0
    // 初始化雷
    function initMine(fx, fy) {
      // 排除点击的那个格子

      // 随机生成雷的位置
      function randomMine(filter) {
        let whileEnd = true
        do {
          let _x = ~~(Math.random() * x)
          let _y = ~~(Math.random() * y)

          if (filter(_x, _y)) {
            let _key = toKey(_x, _y)
            if (!mm[_key]) {
              mm[_key] = {
                x: _x,
                y: _y
              }
            }
            mmLength++
            if (mmLength === mineSize) {
              whileEnd = false
            }
          }
        } while (whileEnd)
      }
      randomMine(function(_x, _y) {
        if (fx === _x && fy === _y) {
          return false
        }
        return true
      })
      console.log(mm)
      for (let key in mm) {
        let data = mm[key]
        var r = gridMap[data.x][data.y]
        r.texture = texture3
      }
    }

    function toKey(x, y) {
      return x + '-' + y
    }

    // 左键
    function onClick() {
      let key = toKey(this._mineX, this._mineY)
      console.log(key)
      if (!initMineFlag) {
        initMineFlag = true
        initMine(this._mineX, this._mineY)
      } else {
        if (!this._mineMark) {
          // this.texture = texture3
          // if (Math.round(Math.random())) {
          //   this.tint = 0xff0000
          // } else {
          //   this.tint = 0xffffff
          // }
          if (mm[key]) {
            this.tint = 0xff0000
          }
        }
      }
    }

    // 右键
    function rightClick() {
      if (this._mineMark) {
        this._mineMark = false
        this.texture = texture
        this.tint = 0xffffff
      } else {
        this._mineMark = true
        this.texture = texture2
        this.tint = 0xffffff
      }
    }
  }
  loadMine()

  // 创造一个容器，里面会包括所有柱子
  blocks = new PIXI.Container()
  stage.addChild(blocks)

  const totalDudes = 15

  for (let i = 0; i < totalDudes; i++) {
    // 渲染的图片
    // create a new Sprite that uses the image name that we just generated as its source
    const dude = PIXI.Sprite.from('eggHead.png')

    // set the anchor point so the texture is centerd on the sprite
    dude.anchor.set(0.5)

    dude._id = '_id' + i

    // 随机大小
    // set a random scale for the dude - no point them all being the same size!
    dude.scale.set(0.3 + Math.random() * 0.8)

    // finally lets set the dude to be at a random position..
    dude.x = Math.random() * app.screen.width
    dude.y = Math.random() * app.screen.height

    // 随机颜色
    dude.tint = Math.random() * 0xffffff

    // create some extra properties that will control movement :
    // create a random direction in radians. This is a number between 0 and PI*2 which is the equivalent of 0 - 360 degrees
    dude.direction = Math.random() * Math.PI * 2

    // this number will be used to modify the direction of the dude over time
    dude.turningSpeed = Math.random() - 0.8

    // create a random speed for the dude between 0 - 2
    dude.speed = 2 + Math.random() * 2

    // finally we push the dude into the aliens array so it it can be easily accessed later
    aliens.push(dude)

    // 点击有效
    dude.interactive = true
    // 鼠标移动上去变成小手
    dude.buttonMode = true
    dude.on('pointerdown', function() {
      console.log(this)
      console.log(arguments)
    })

    app.stage.addChild(dude)
    // blocks.addChild(dude)
  }

  const style = new PIXI.TextStyle({
    fontFamily: 'Arial',
    fontSize: 18,
    fontStyle: 'italic',
    fontWeight: 'bold',
    fill: ['#ffffff', '#00ff99'], // gradient
    stroke: '#4a1850',
    strokeThickness: 5,
    dropShadow: true,
    dropShadowColor: '#000000',
    dropShadowBlur: 4,
    dropShadowAngle: Math.PI / 6,
    dropShadowDistance: 6,
    wordWrap: true,
    wordWrapWidth: 440
  })
  // 添加文字
  const basicText = new PIXI.Text('Basic text in pixi', style)
  basicText.x = 50
  basicText.y = 100
  app.stage.addChild(basicText)

  // create a bounding box for the little dudes
  const dudeBoundsPadding = 100
  const dudeBounds = new PIXI.Rectangle(
    -dudeBoundsPadding,
    -dudeBoundsPadding,
    app.screen.width + dudeBoundsPadding * 2,
    app.screen.height + dudeBoundsPadding * 2
  )

  // 碰撞超过3次，就隐藏
  const blockMap = {}

  app.ticker.add(() => {
    // iterate through the dudes and update their position
    for (let i = 0; i < aliens.length; i++) {
      const dude = aliens[i]
      dude.direction += dude.turningSpeed * 0.01
      dude.x += Math.sin(dude.direction) * dude.speed
      dude.y += Math.cos(dude.direction) * dude.speed
      dude.rotation = -dude.direction - Math.PI / 2

      // wrap the dudes by testing their bounds...
      if (dude.x < dudeBounds.x) {
        dude.x += dudeBounds.width
      } else if (dude.x > dudeBounds.x + dudeBounds.width) {
        dude.x -= dudeBounds.width
      }

      if (dude.y < dudeBounds.y) {
        dude.y += dudeBounds.height
      } else if (dude.y > dudeBounds.y + dudeBounds.height) {
        dude.y -= dudeBounds.height
      }

      // 检测是否碰撞，返回true表示产生了碰撞
      let pixieVsBlock = blocks.children.some(function(block, index, array) {
        if (!block.visible) {
          return false
        }
        // console.log(block)
        let isB = b.hitTestRectangle(dude, block, true)
        if (isB) {
          if (blockMap[block._id]) {
            blockMap[block._id] = blockMap[block._id] + 1
            // 超过3次就隐藏
            if (blockMap[block._id] >= 3) {
              // 隐藏
              block.visible = false
              // 销毁
              block.destroy()
            }
          } else {
            blockMap[block._id] = 1
          }
        }
        return isB
      })

      // 检测到了，并且精灵是可见的
      if (pixieVsBlock && dude.visible) {
        // 设置精灵不可见
        dude.visible = false
        dude.destroy()

        // 从数组中删掉
        aliens.splice(i, 1)
      }
    }
  })

  // 创建一个砖块
  let block = PIXI.Sprite.from('greenBlock.png')
  // 砖块的位置
  block.x = 100
  block.y = 100
  block._id = 1
  let block2 = PIXI.Sprite.from('greenBlock.png')
  // 砖块的位置
  block2.x = 100
  block2.y = 164
  block2._id = 2

  let block3 = PIXI.Sprite.from('greenBlock.png')
  // 砖块的位置
  block3.x = 164
  block3.y = 164
  block3._id = 3
  // block3.width = 320
  // block3.height = 320

  // 添加到容器中
  blocks.addChild(block)
  blocks.addChild(block2)
  blocks.addChild(block3)

  // //几何图形
  // const borderline = new PIXI.Graphics()
  // borderline.lineStyle(2, 0xaaaaaa, 0.5) //边线(宽度，颜色，透明度)
  // borderline.beginFill(0xffffff) //填充
  // // 长方形
  // borderline.drawRect(100, 100, 200, 300) //x,y,w,h
  // // 线段
  // // borderline.moveTo(100, 100) //x,y 开始
  // // borderline.lineTo(100, 200) //x,y 结束
  // borderline.endFill()
  // // app.stage.addChild(borderline) //添加到舞台中
  // blocks.addChild(borderline)
}

/*
1.鼠标左键触发事件：

click：点击事件

mousedown：鼠标按下

mousemove：鼠标移动

mouseout：鼠标移出

mouseover：鼠标经过

mouseup：鼠标松开

mouseupoutside：鼠标按下，移出对象松开

2.鼠标右键触发事件：

rightclick：点击事件

rightdown：鼠标按下

rightup：鼠标松开

rightupoutside：鼠标按下，移出对象松开

3.触摸屏触发事件：

touchcancel：触摸系统cancels键

touchend：触摸结束

touchendoutside：触摸开始，移出对象松开

touchmove：触摸移动

touchstart：触摸开始

4.兼容鼠标和触摸屏的共同触发：

pointercancel：触发系统cancels键

pointerdown：触发按下

pointermove：触发移动

pointerout：触发移出

pointerover：触发经过

pointertap：触发点击

pointerup：触发松开

*/
